<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="success"
                   size="small"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导出
        </el-button>
        <el-button type="success"
                   size="small"
                   plain
                   icon="el-icon-download"
                   @click="handleExportTodo">导出所有未处理配货订单
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          icon="el-icon-setting"
          type="danger"
          size="small"
          @click.stop="handleVoid(row)"
        >作废
        </el-button>
      </template>
      <template slot-scope="{row}" slot="expand">
        <avue-crud :option="styleOptions"
                   style="margin-left: 100px"
                   :data="JSON.parse(row.associatedGoods)"
                   ref="crud">
          <template slot-scope="{row}" slot="pictureUrl">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.pictureUrl"
              :fit="cover"></el-image>
          </template>
          <template slot-scope="{row}" slot="value">
            <el-tag style="margin-right: 5px" :key="i" v-for="(item, i) in JSON.parse(row.value)">{{item}}</el-tag>
          </template>
          <template slot-scope="{row}" slot="price">
            <el-tag>NT$ {{row.price}}</el-tag>
          </template>
        </avue-crud>
        <div style="margin-left: 100px">
          <span style="font-size: 15px; font-weight: bold">收件人: {{ row.receiverName }} {{ row.receiverPhone }}</span>
          <span style="font-size: 15px; font-weight: bold"><br>电子邮箱: {{ row.receiverEmail ? row.receiverEmail : '无' }}</span>
          <span style="font-size: 15px; font-weight: bold"><br>配送地址: {{ row.shippingAddress }}</span>
          <span style="font-size: 15px; font-weight: bold"><br>备注: {{ row.remark ? row.remark : '无' }}</span>
        </div>
      </template>
      <template slot-scope="{row}" slot="id">
        <el-tag>{{row.id}}</el-tag>
      </template>
      <template slot-scope="{row}" slot="totalAmount">
        <el-tag>NT$ {{row.totalAmount}}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="status">
        <span>
          <el-tag
            v-if="row.status === 1"
            size="small"
          >{{row.statusName}}</el-tag>
          <el-tag
            v-else-if="row.status === 2"
            size="small"
            type="danger"
          >{{row.statusName}}</el-tag>
          <el-tag
            v-else
            size="small"
            type="success"
          >{{row.statusName}}</el-tag>&nbsp;&nbsp;
        </span>
      </template>
      <template slot-scope="{row}"
                slot="payStatus">
        <span>
          <el-tag
            v-if="row.payStatus === 0"
            size="small"
            type="info"
          >{{row.payStatusName}}</el-tag>
          <el-tag
            v-else
            size="small"
            type="success"
          >{{row.payStatusName}}</el-tag>&nbsp;&nbsp;
        </span>
      </template>
      <template slot-scope="{row}"
                slot="shipStatus">
        <el-select v-model="row.shipStatus" @change="((val) => {handleShipStatusChange(val, row.id)})">
          <el-option
            v-for="item in shipStatusDic"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="{row}"
                slot="shipTypeName">
        <el-tag
          size="small"
        >{{row.shipTypeName}}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="area">
        <el-tag
          size="small"
        >台湾</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="isNew">
        <span v-if="row.isNew === 1"><el-tag type="success" size="medium">新用户</el-tag></span>
        <span v-else>
          <el-tag type="danger" size="medium">老用户</el-tag>
          <el-button style="margin-left: 5px" type="primary" size="small" @click="historyOrder(row)">历史订单</el-button>
        </span>
      </template>
      <template slot-scope="{type,disabled}" slot="goodsCountForm">
        <el-tag>{{form.goodsCount}}</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="fromDomainForm">
        <el-tag>{{form.fromDomain}}</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="fromIpForm">
        <el-tag v-if="form.fromIp">{{form.fromIp}}</el-tag>
        <el-tag v-else>unknown</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="shipTypeNameForm">
        <el-tag>{{form.shipTypeName}}</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="idForm">
        <el-tag>{{form.id}}</el-tag>
      </template>
      <template slot-scope="{type,disabled}" slot="totalAmountForm">
        <el-tag>NT$ {{form.totalAmount}}</el-tag>
      </template>
<!--      <template slot-scope="{row}" slot="menu">-->
<!--        <el-button-->
<!--          icon="el-icon-s-promotion"-->
<!--          type="primary"-->
<!--          size="small"-->
<!--        >发货-->
<!--        </el-button>-->
<!--      </template>-->
    </avue-crud>
    <el-dialog
      title="历史订单"
      width="70%"
      @close="dialogViewVisible=false"
      :visible.sync="dialogViewVisible">
      <basic-container>
        <avue-crud :option="optionHistory"
                   :data="dataHistory"
                   :page="pageHistory"
                   :before-open="beforeOpenHistory"
                   v-model="formHistory"
                   ref="crudHistory"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoadHistory">
          <template slot-scope="{row}" slot="menu">
            <el-button
              icon="el-icon-setting"
              type="danger"
              size="small"
              @click.stop="handleVoid(row)"
            >作废
            </el-button>
          </template>
          <template slot-scope="{row}"
                    slot="shipStatus">
            <el-select v-model="row.shipStatus" @change="((val) => {handleShipStatusChange(val, row.id)})">
              <el-option
                v-for="item in shipStatusDic"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
          <template slot-scope="{row}" slot="expand">
            <avue-crud :option="styleOptions"
                       style="margin-left: 100px"
                       :data="JSON.parse(row.associatedGoods)"
                       ref="crudHistory">
              <template slot-scope="{row}" slot="pictureUrl">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="row.pictureUrl"
                  :fit="cover"></el-image>
              </template>
              <template slot-scope="{row}" slot="value">
                <el-tag style="margin-right: 5px" :key="i" v-for="(item, i) in JSON.parse(row.value)">{{item}}</el-tag>
              </template>
              <template slot-scope="{row}" slot="price">
                <el-tag>NT$ {{row.price}}</el-tag>
              </template>
            </avue-crud>
            <div style="margin-left: 100px">
              <span style="font-size: 15px; font-weight: bold">收件人: {{ row.receiverName }} {{ row.receiverPhone }}</span>
              <span style="font-size: 15px; font-weight: bold"><br>电子邮箱: {{ row.receiverEmail ? row.receiverEmail : '无' }}</span>
              <span style="font-size: 15px; font-weight: bold"><br>配送地址: {{ row.shippingAddress }}</span>
              <span style="font-size: 15px; font-weight: bold"><br>备注: {{ row.remark ? row.remark : '无' }}</span>
            </div>
          </template>
        </avue-crud>
      </basic-container>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogViewVisible=false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="订单作废"
      width="40%"
      @close="dialogVoidVisible=false"
      :visible.sync="dialogVoidVisible">
      <basic-container style="font-weight: bold; font-size: 15px;">
        <el-form :model="voidForm">
          <el-form-item label="备注">
            <el-input type="textarea" v-model="voidForm.voidRemark" :maxlength="250">
            </el-input>
          </el-form-item>
        </el-form>
      </basic-container>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="info" @click="dialogVoidVisible=false">取 消</el-button>
        <el-button size="small" type="primary" @click="voidConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getHistoryList,
  changeOrdersStatus,
  changeOrdersStatusTodo
} from "@/api/order/order";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";
import {getLocation} from "@/api/other/ip";

  export default {
    data() {
      return {
        voidForm: {},
        voidMessage: '',
        dialogVoidVisible: false,
        formHistory: {},
        pageHistory: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        dataHistory: [],
        optionHistory: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          expand: true,
          expandRowKeys:[1],
          rowKey: 'id',
          searchMenuSpan: 3,
          tip: false,
          fit:false,
          border: true,
          index: false,
          viewBtn: false,
          addBtn: false,
          delBtn: false,
          editBtn: false,
          menuType: 'icon',
          selection: true,
          column: [
            {
              label: "订单编号",
              prop: "code",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '180px',
              display: false
            },
            {
              label: "商品名称",
              prop: "goodsName",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '180px',
              display: false
            },
            {
              label: "商品数量",
              prop: "goodsCount",
              editDisabled: true,
              formslot: true,
              slot: true,
              display: false
            },
            {
              label: "总金额",
              prop: "totalAmount",
              editDisabled: true,
              formslot: true,
              width: '130px',
              slot: true,
              display: false
            },
            {
              label: "下单时间",
              prop: "createTime",
              width: '150px',
              display: false
            },
            {
              label: "订单状态",
              prop: "shipStatus",
              slot: true,
              type: 'select',
              width: '130px',
              dicData: [],
              display: false
            },
            {
              label: "IP",
              prop: "fromIp",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '130px',
              display: false
            }
          ]
        },
        dialogViewVisible: false,
        historyOrderList: [],
        shipStatusDic: [
          {
            label: "待确认",
            value: 0
          },
          {
            label: "待发货",
            value: 1
          },
          {
            label: "配货中",
            value: 2
          },
          {
            label: "待收货",
            value: 3
          },
          {
            label: "已完成",
            value: 4
          },
          {
            label: "已退货",
            value: 5
          }
        ],
        statusDic: [
          {
            label: "正常",
            value: 1
          },
          {
            label: "作废",
            value: 2
          }
        ],
        styleOptions: {
          tip: false,
          index: false,
          menu: false,
          addBtn: false,
          filterBtn: false,
          refreshBtn: false,
          operationBtn: false,
          columnBtn: false,
          column: [
            {
              label: "商品",
              prop: "goodsName",
            },
            {
              label: "图片路径",
              prop: "pictureUrl",
              slot: true
            },
            {
              label: "商品规格",
              prop: "value",
            },
            {
              label: "价格",
              prop: "price",
            }
          ]
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          expand: true,
          expandRowKeys:[1],
          rowKey: 'id',
          searchMenuSpan: 6,
          tip: false,
          fit:false,
          border: true,
          index: false,
          viewBtn: false,
          addBtn: false,
          delBtn: false,
          editBtn: true,
          menuType: 'icon',
          selection: true,
          column: [
            {
              label: "国家/地区",
              prop: "area",
              slot: true,
              width: '130px',
              display: false
            },
            {
              label: "订单编号",
              prop: "code",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '180px',
              display: false
            },
            {
              label: "商品名称",
              prop: "goodsName",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '180px',
              display: false
            },
            {
              label: "出单人",
              prop: "fromUser",
              type: "select",
              dicUrl: "/api/blade-user/user-list-by-dept",
              props: {
                label: "name",
                value: "id"
              },
              search: true,
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '130px',
              display: false
            },
            {
              label: "公司",
              prop: "tenantId",
              type: "tree",
              dicUrl: "/api/blade-system/tenant/select",
              props: {
                label: "tenantName",
                value: "tenantId"
              },
              display: false,
              search: true,
              rules: [{
                required: true,
                message: "请输入所属租户",
                trigger: "click"
              }],
              hide: true
            },
            {
              label: "商品数量",
              prop: "goodsCount",
              editDisabled: true,
              formslot: true,
              slot: true,
              display: false
            },
            {
              label: "总金额",
              prop: "totalAmount",
              editDisabled: true,
              formslot: true,
              width: '130px',
              slot: true,
              display: false
            },
            {
              label: "新用户",
              prop: "isNew",
              slot: true,
              width: '180px',
              display: false
            },
            {
              label: "运送方式",
              prop: "shipTypeName",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '130px',
              display: false
            },
            {
              label: "订单状态",
              prop: "shipStatus",
              slot: true,
              search: true,
              type: 'select',
              width: '130px',
              dicData: [],
              display: false
            },
            {
              label: "下单时间",
              prop: "createTime",
              width: '150px',
              display: false
            },
            {
              label: "来源域名",
              prop: "fromDomain",
              editDisabled: true,
              formslot: true,
              slot: true,
              hide: true
            },
            {
              label: "IP",
              prop: "fromIp",
              editDisabled: true,
              formslot: true,
              slot: true,
              width: '130px',
              display: false
            },
            {
              label: "收件人",
              prop: "receiverName",
              hide: true,
              search: true
            },
            {
              label: "联系电话",
              prop: "receiverPhone",
              hide: true,
              search: true
            },
            {
              label: "运送地址",
              prop: "shippingAddress",
              hide: true
            },
            {
              label: "备注",
              prop: "remark",
              hide: true
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.order_add, false),
          viewBtn: this.vaildData(this.permission.order_view, false),
          delBtn: this.vaildData(this.permission.order_delete, false),
          editBtn: this.vaildData(this.permission.order_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    // watch: {
    //   // dataList为table的数据对象data
    //   data() {
    //     // 解决横向滚动时，列没对齐的问题
    //     this.$nextTick(() => {
    //       setTimeout(() => {
    //         let lastColEl = document.querySelector('.el-table__header colgroup col:last-child')
    //         if (lastColEl) {
    //           // 最后一列的宽度加上滚动条的宽度
    //           lastColEl.width = Number(lastColEl.width) + 6 // 6为滚动条宽度
    //         }
    //       }, 1000)
    //     })
    //   },
    //   dataHistory() {
    //     // 解决横向滚动时，列没对齐的问题
    //     this.$nextTick(() => {
    //       setTimeout(() => {
    //         let lastColEl = document.querySelector('.el-table__header colgroup col:last-child')
    //         if (lastColEl) {
    //           // 最后一列的宽度加上滚动条的宽度
    //           lastColEl.width = Number(lastColEl.width) + 6 // 6为滚动条宽度
    //         }
    //       }, 1000)
    //     })
    //   }
    // },
    methods: {
      handleExport() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("是否导出订单数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/celery-order/order/export-order?blade-auth=${getToken()}&orderIds=${this.ids}`);
          setTimeout(() => {
            this.$confirm("是否修改订单状态?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              changeOrdersStatus(this.ids, this.statusDic[1].value).then(() => {
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              }, error => {
                window.console.log(error);
              })
            });
          }, 1000)
        });
      },
      handleExportTodo() {
        this.$confirm("是否导出所有待配货订单数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/celery-order/order/export-order-todo?blade-auth=${getToken()}&tenantId=${this.query.tenantId ? this.query.tenantId : ''}&fromUser=${this.query.fromUser ? this.query.fromUser : ''}`);
          setTimeout(() => {
            this.$confirm("是否修改订单状态?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              changeOrdersStatusTodo(this.statusDic[1].value, this.query.tenantId ? this.query.tenantId : '', this.query.fromUser ? this.query.fromUser : '').then(() => {
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              }, error => {
                window.console.log(error);
              })
            });
          }, 1000)
        });
      },
      handleVoid(row) {
        this.voidForm = {
          id: row.id,
          voidRemark: ''
        }
        this.dialogVoidVisible = true
      },
      voidConfirm() {
        const params = this.voidForm
        params.status = this.statusDic[1].value
        update(params).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
        this.dialogVoidVisible = false
      },
      historyOrder(order) {
        this.dialogViewVisible = true
        getHistoryList(this.pageHistory.currentPage, this.pageHistory.pageSize, {
          receiverPhone: order.receiverPhone,
          receiverEmail: order.receiverEmail,
          fromIp: order.fromIp
        }).then(res => {
          const data = res.data.data;
          this.pageHistory.total = data.total;
          this.dataHistory = data.records;
          const column = this.findObject(this.optionHistory.column, "shipStatus");
          column.dicData = this.shipStatusDic;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleShipStatusChange(val, id) {
        update({id: id, shipStatus: val}).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      beforeOpenHistory(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.formHistory.id).then(res => {
            this.formHistory = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      selectionHistoryClear() {
        this.selectionList = [];
        this.$refs.crudHistory.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      getOrderIpLocation() {
        this.data.map(item => {
          setTimeout(() => {
            getLocation(item.fromIp).then(res => {
              const data = res.data
              if (data.status === 0) {
                item.fromIp = `${data.result.ad_info.city} -  ${item.fromIp}`
              }
            })
          }, 500)
        })
      },
      onLoad(page, params = {}) {
        this.loading = true;
        params.status = this.statusDic[0].value
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          // this.getOrderIpLocation()
          const column = this.findObject(this.option.column, "shipStatus");
          column.dicData = this.shipStatusDic;
          this.loading = false;
          this.selectionClear();
        });
      },
      onLoadHistory(page, params = {}) {
        this.loading = true;
        params.status = this.statusDic[0].value
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          const column = this.findObject(this.option.column, "shipStatus");
          column.dicData = this.shipStatusDic;
          this.loading = false;
          this.selectionHistoryClear();
        });
      }
    }
  };
</script>

<style>
.avue-crud__menu {
  min-height: 0;
}
.avue-crud__pagination {
  padding: 10px 0 10px 0;
}
</style>
